package com.oa.crm.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.crm.common.CrmUtils;
import com.oa.crm.entity.Customer;
import com.oa.crm.service.CustomerService;
import com.oa.crm.service.RegionService;
import com.oa.crm.vo.CustomerAddVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@RestController
@RequestMapping(value = "/**/oa/crm/customer")
@Api(tags = {"客户信息表-操作接口"})
public class CustomerController {

    static Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RegionService regionService;

    @ApiOperation(value = "客户信息表-查询列表", notes = " ")
    @ApiEntityParams(Customer.class)
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listCustomer(@ApiIgnore @RequestParam Map<String, Object> params) {
//        User user = LoginUtils.getCurrentUserInfo();
        RequestUtils.transformArray(params, "customerIds");
        //权限控制
        User user = LoginUtils.getCurrentUserInfo();
        //用户id
        String userid = user.getUserid();
        //部门id
        String deptid = user.getDeptid();
        //角色id
        String roleid = LoginUtils.getGuestRoleid();

        params.put("userid", userid);
        params.put("deptid", deptid);
        params.put("roleid", roleid);

        List<Map<String, Object>> customerList = customerService.selectCustomerByAuthority(params);

        //查询对应的联系人
        List<Map<String, Object>> newCustomerList = customerService.selectCustomerContacter(customerList);

        return Result.ok("query-ok", "查询成功").setData(newCustomerList);
    }


    @RequestMapping(value = "/getExitCustomerCount", method = RequestMethod.GET)
    public Result getExitCustomerCount(@RequestParam Map<String, Object> customer) {
        long count = customerService.countByWhere((Customer) customer);

        return Result.ok().setData(count);
    }

    @RequestMapping(value = "/getNewestCustomer", method = RequestMethod.GET)
    public Result getNewestCustomer(@RequestParam Map<String, Object> customer) {
        List<Map<String, Object>> listMap = customerService.getNewestCustomer(customer);

        return Result.ok().setData(listMap);
    }

    @ApiOperation(value = "客户信息表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addCustomer(@RequestBody CustomerAddVo customerAddVo, HttpServletRequest httpServletRequest) {


        if (StringUtils.isEmpty(customerAddVo.getCustomer().getCustomerId())) {
            customerAddVo.getCustomer().setCustomerId(customerService.createKey("customerId"));
        } else {
            Customer customerQuery = new Customer(customerAddVo.getCustomer().getCustomerId());
            if (customerService.countByWhere(customerQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        try {
            customerService.insertCustomer(customerAddVo, CrmUtils.getIpAddress(httpServletRequest));

        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
        }


        return Result.ok("add-ok", "添加成功！").setData(customerAddVo);
    }

    @ApiOperation(value = "设置客户的是否关注状态", notes = "addCustomer,主键如果为空，后台自动生成")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/isAttention", method = RequestMethod.POST)
    public Result isAttention(@RequestBody Map<String, Object> customer) {


        customerService.isAttention(customer);

        return Result.ok();
    }

    @ApiOperation(value = "客户信息表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delCustomer(@RequestBody Customer customer) {
        customerService.removeById(customer);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "客户信息表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editCustomer(CustomerAddVo customerAddVo, HttpServletRequest httpServletRequest) {
        try {
            customerService.editCustomer(customerAddVo, CrmUtils.getIpAddress(httpServletRequest));
        } catch (JsonProcessingException | IllegalAccessException e) {
            logger.error(e.getMessage());
        }
        return Result.ok("edit-ok", "修改成功！").setData(customerAddVo);
    }

    @ApiOperation(value = "查询顶层区域", notes = "查询顶层区域")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/getRegionByParentId", method = RequestMethod.GET)
    public Result getRegionByParentId(@RequestParam Map<String, Object> param) {
        QueryWrapper<Customer> qw = QueryTools.initQueryWrapper(Customer.class, param);
        IPage page = QueryTools.initPage(param);


        List<Map<String, Object>> mapList = null;

        mapList = regionService.selectListMapByWhere(page, qw, param);

        return Result.ok("query-ok", "查询顶层区域成功").setData(mapList).setTotal(page.getTotal());
    }

    @ApiOperation(value = "客户信息表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = Customer.class, props = {}, remark = "客户信息表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        customerService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "客户信息表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelCustomer(@RequestBody List<Customer> customers) {
        User user = LoginUtils.getCurrentUserInfo();
        if (customers.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<Customer> datasDb = customerService.listByIds(customers.stream().map(i -> i.getCustomerId()).collect(Collectors.toList()));

        List<Customer> can = new ArrayList<>();
        List<Customer> no = new ArrayList<>();
        for (Customer data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            customerService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getCustomerId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "客户信息表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Customer.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(Customer customer) {
        Customer data = (Customer) customerService.getById(customer);
        return Result.ok().setData(data);
    }

}
